/**
 * Copyright 2009 - Morten Udnæs
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.javabatch.petstore.process;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.javabatch.fileio.FieldError;
import com.javabatch.fileio.FileBuffer;
import com.javabatch.fileio.FileStore;
import com.javabatch.fileio.RecordBasedFileStore;
import com.javabatch.petstore.records.InventoryRecord;
import com.javabatch.petstore.records.PriceRecord;
import com.javabatch.petstore.records.Record;

public class CreateInventoryFileProcess implements BatchProcess {
	private FileStore priceStore;
	private FileStore inventoryStore;
	
	public CreateInventoryFileProcess(String priceFile, String inventoryFile) {
		priceStore = new RecordBasedFileStore(priceFile, RecordBasedFileStore.READ_ACCESS, 
				PriceRecord.getLengthAndValidateRecord());
		inventoryStore = new RecordBasedFileStore(inventoryFile, RecordBasedFileStore.WRITE_ACCESS,
		InventoryRecord.getLengthAndValidateRecord());
	}

	@Override
	public List execute(List<Record> records) {
		Random rnd = new Random();
		List<Integer> results = new ArrayList<Integer>();
		List<FieldError> errors = new ArrayList<FieldError>();
		Integer inventoryID = new Integer(0);
		
		priceStore.open();
		inventoryStore.open();
		
		FileBuffer priceBuffer = null;
		
		while (priceStore.hasMore()) {
			inventoryID++;
			priceBuffer = priceStore.readNext();
			FileBuffer inventoryBuffer = new FileBuffer();
			
			InventoryRecord.ANIMAL_ID.write(inventoryBuffer, 
					PriceRecord.ANIMAL_ID.read(priceBuffer, errors));
			InventoryRecord.INVENTORY_ID.write(inventoryBuffer, 
					inventoryID.toString());
			InventoryRecord.STOCK.write(inventoryBuffer, Integer.toString(rnd.nextInt(1000)));
			
			inventoryStore.write(inventoryBuffer);
			
			if (errors.size() > 0 ) {
				throw new RuntimeException("Something went wrong!");
			}
			
			if (inventoryID % 10000 == 0) {
				System.out.println("Current inventoryID"+ inventoryID);
			}
		}
		priceStore.close();
		inventoryStore.close();
		results.add(inventoryID);
		
		return results;
		
	}

	@Override
	public List<Object> prepare(List<Record> records) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void release(List<Record> records) {
		// TODO Auto-generated method stub
		
	}

}
